package com.hk.Mgr.web.controller.app;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

import com.hk.commons.*;
import com.hk.commons.utils.IPUtil;
import com.hk.commons.utils.TerminalTypeEnum;
import com.hk.commons.vo.yingmi.TerminalRequestDTO;
import com.hk.context.RiskEvaluationContext;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.hk.Mgr.web.message.kyc.AnswerPhoneReq;
import com.hk.Mgr.web.message.kyc.KycRes;
import com.hk.Mgr.web.message.kyc.QuestionPhoneRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.entity.Answer;
import com.hk.service.sys.IAnswer;

import javax.servlet.http.HttpServletRequest;

/**
 * @author psx 职务实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.App + "/kycCtrl")
public class AppKycCtrl extends BaseCtrl {

    public static final int KYC_QUESTION_LENGTH = 10;
    private Logger logger = LoggerFactory.getLogger(AppKycCtrl.class);

    @Autowired
    private IAnswer answerService;

    @Autowired
    private RiskEvaluationContext riskEvaluationContext;

    /**
     * 获取KYC问题，不需要输入参数，直接把所有问题返回
     *
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBase<List<QuestionPhoneRes>> list(Long groupId) {

        ResponseBase<List<QuestionPhoneRes>> resp = new ResponseBase<List<QuestionPhoneRes>>();
        List<QuestionPhoneRes> result = riskEvaluationContext.listQuestions(groupId);

        resp.setResult(result);
        resp.setResultCode(ResultCode.SUCC.getCode());

        return resp;
    }


    /**
     * 保存用户答题的答案，一次回答所有问题
     *
     * @param req ~> mobileId, selectionArr 1,2,3,4,1,2,3,4,1,2
     */
    @RequestMapping(value = "/answerAll", method = RequestMethod.POST)
    @ResponseBody
    public ResponseBase<KycRes> answerAll(HttpServletRequest request, @RequestBody AnswerPhoneReq req) {
        ResponseBase<KycRes> result = new ResponseBase<KycRes>();

        String selection = req.getSelectionArray();
        if (StringUtils.isBlank(selection)) {
            result.setMsg("参数 selectionArray不能为空！");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        String[] selectionArr = selection.split(",");
        if (selectionArr.length != KYC_QUESTION_LENGTH) {
            logger.error("app/kycCtrl/answerAll answer length error  "
                    + " current length is " + selectionArr.length
                    + " expect length is " + KYC_QUESTION_LENGTH);
            result.setMsg("答题未完成！");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        KycRes calcResult = riskEvaluationContext.calcRiskLevel(selectionArr,req.getGroupId());

        // without userId calc directly
        if (StringUtils.isBlank(req.getUserId())) {
            result.setResult(calcResult);
            result.setResultCode(ResultCode.SUCC.getCode());
            return result;
        }

        Long userId = Long.valueOf(req.getUserId());
        logger.info("app/kcyCtrl/answerAll 输入参数为：userId = " + userId + " selection = " + selection);

        TerminalRequestDTO terminalReq = new TerminalRequestDTO(request);
        terminalReq.setMobileId(req.getMobileId());

        if(StringUtils.isNoneBlank(req.getTerminalIP())){
            terminalReq.setTerminalIP(req.getTerminalIP());
        }

        boolean storeRiskLevelResult = riskEvaluationContext.storeRiskLevelResult(
                userId, selection, calcResult, terminalReq);

        if (!storeRiskLevelResult) {
            result.setMsg("保存风险测评结果失败");
            result.setResultCode(ResultCode.FAILED.getCode());
            return result;
        }

        result.setResult(calcResult);
        result.setResultCode(ResultCode.SUCC.getCode());
        return result;
    }


    /**
     * 计算用户的风险等级
     *
     * @param userId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getRiskLevel", method = RequestMethod.GET)
    public ResponseBase<KycRes> getRiskLevel(@RequestParam Long userId) {
        ResponseBase<KycRes> result = new ResponseBase<KycRes>();

        if (userId == null) {
            result.setMsg("参数userId 不能为空！");
            result.setResultCode(ResultCode.PARAM_ERROR.getCode());
            return result;
        }

        Answer an = answerService.getByUserId(userId);

        if (an == null) {
            result.setMsg("KYC尚未完成");
            result.setResultCode(ResultCode.FAILED.getCode());
            return result;
        }

        KycRes kycRes = new KycRes();
        kycRes.setRiskLevel(an.getScore());
        kycRes.setDesc(an.getScoreDesc());
        kycRes.setLongDesc(an.getScoreLongDesc());

        result.setResult(kycRes);
        result.setResultCode(ResultCode.SUCC.getCode());


        logger.info(" get kyc message : userId = " + userId + "   Kyc 总得分为" + kycRes.toString());

        return result;
    }



}


